package com.book.common.result;

import com.google.common.collect.Maps;
import lombok.Data;

import java.io.Serializable;
import java.util.Map;

/**
 * Description：
 * @Author： leo.xiong
 * @CreateDate： 2020/4/2 14:44
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Data
public class RestResponse<T> implements Serializable {
    private static final long serialVersionUID = -634504756728905706L;
    /**
     * 消息结果
     */
    protected boolean result;
    /**
     * 错误码
     */
    protected String errorCode;
    /**
     * 错误描述
     */
    protected String errorMsg;
    /**
     * 响应结果
     */
    protected T data;
    /**
     * 元数据
     */
    protected Map<String, Object> meta;

    public Map<String, Object> getMeta() {
        return this.meta;
    }

    /**
     * 添加元数据
     *
     * @param name 字段名
     * @param obj  值
     * @return this
     */
    public RestResponse<T> addMeta(String name, Object obj) {
        if (null == this.meta) {
            this.meta = Maps.newHashMap();
        }
        this.meta.put(name, obj);
        return this;
    }

    /**
     * 添加元数据
     *
     * @param meta 值
     * @return this
     */
    public RestResponse<T> addMeta(Map<String, Object> meta) {
        meta.entrySet().iterator().forEachRemaining(entry -> addMeta(entry.getKey(), entry.getValue()));
        return this;
    }

    public boolean isFailed() {
        return !this.result;
    }

    public boolean isSuccess() {
        return this.result;
    }

    @Override
    public String toString() {
        return "RestResponse{" +
                "result=" + result +
                ", errorCode='" + errorCode + '\'' +
                ", errorMsg='" + errorMsg + '\'' +
                ", data=" + data +
                ", meta=" + meta +
                '}';
    }
}
